package com.farina.cryptobox;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.farina.cryptobox.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class ViewActivity extends Activity {

	private String username="";
	private String key="";
	private String oldtitle="";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		String usn = intent.getStringExtra(AccountManager.EXTRA_MESSAGE_USN2);
		String key = intent.getStringExtra(AccountManager.EXTRA_MESSAGE_PPH);
		String info = intent.getStringExtra(AccountManager.EXTRA_MESSAGE_INFO);
		oldtitle = intent.getStringExtra(AccountManager.EXTRA_MESSAGE_TITLE);
		this.username=usn;
		this.key=key;
		setContentView(R.layout.activity_view);

		EditText titleText = (EditText) findViewById(R.id.titleViewField);
		EditText usnText = (EditText) findViewById(R.id.usnViewField);
		EditText pwdText = (EditText) findViewById(R.id.pwdViewField);
		EditText infoText = (EditText) findViewById(R.id.otherViewField);

		if(info.equals("add")){
			ToggleButton tg=(ToggleButton) findViewById(R.id.modOnOfViewButton);
			Button modify=(Button) findViewById(R.id.modViewButton);
			tg.setEnabled(false);
			modify.setEnabled(false);
		}
		if(info.equals("view")){

			titleText.setText(oldtitle);
			String buffer=loadAllInstances(key, cryptMD5(username)+"_instances.txt");   	
			
			String[] buffArray=buffer.split("\n");
			
			for(int i=0;i<buffArray.length; i++){
				if(buffArray[i].equals("1"+oldtitle)){
					usnText.setText(buffArray[i+1].substring(1));
					pwdText.setText(buffArray[i+2].substring(1));
					infoText.setText(buffArray[i+3].substring(1));
					break;
				}
			}
			buffer="";
			buffArray=null;
			Button add=(Button) findViewById(R.id.addViewButton);
			add.setEnabled(false);
			usnText.setEnabled(false);
			pwdText.setEnabled(false);
			infoText.setEnabled(false);
			titleText.setEnabled(false);
			usnText.setFocusableInTouchMode(false);
			pwdText.setFocusableInTouchMode(false);
			infoText.setFocusableInTouchMode(false);
			titleText.setFocusableInTouchMode(false);
		}


	}
	
	@Override
    protected void onStop() {
        super.onStop();
        this.finish();
    }
	
	@Override
    protected void onPause() {
        super.onStop();
        this.finish();
    }
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_view, menu);
		return true;
	}
	
	public String cryptMD5(String s){
		String usnHash="";
		try {
			usnHash=CryptoFunction.MD5(s);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return usnHash;
		
	}

	public void modify(View view) {
		EditText titleText = (EditText) findViewById(R.id.titleViewField);
		EditText usnText = (EditText) findViewById(R.id.usnViewField);
		EditText pwdText = (EditText) findViewById(R.id.pwdViewField);
		EditText infoText = (EditText) findViewById(R.id.otherViewField);
		
		String buffer=loadAllInstances(key, cryptMD5(username)+"_instances.txt");		
		String[] buffArray=buffer.split("\n");
		
		for(int i=0;i<buffArray.length; i++){
			if(buffArray[i].equals("1"+oldtitle)){
				buffArray[i]="1"+titleText.getText().toString();
				buffArray[i+1]="2"+usnText.getText().toString();
				buffArray[i+2]="3"+pwdText.getText().toString();
				buffArray[i+3]="4"+infoText.getText().toString();
				break;
			}
		}
		buffer="";
		for(int i=0;i<buffArray.length; i++) buffer=buffer+buffArray[i]+"\n";
		writeAllInstances(key, buffer, cryptMD5(username)+"_instances.txt");
		
		if(!oldtitle.equals(titleText.getText().toString())){
			
			buffer=loadAllInstances(key, cryptMD5(username)+"_titles.txt");
			String[] buffArray2=buffer.split("\n");
			
			for(int i=0;i<buffArray2.length; i++){
				if(buffArray2[i].equals(oldtitle)){
					buffArray2[i]=titleText.getText().toString();
					break;
				}
			}
			buffer="";
			for(int i=0;i<buffArray2.length; i++) buffer=buffer+buffArray2[i]+"\n";
			writeAllInstances(key, buffer, cryptMD5(username)+"_titles.txt");
			buffArray2=null;
		}
		buffer="";
		buffArray=null;
		
		showToast("Data Successfully Modified!");

	}

	public void edit(View view) {
		EditText titleText = (EditText) findViewById(R.id.titleViewField);
		EditText usnText = (EditText) findViewById(R.id.usnViewField);
		EditText pwdText = (EditText) findViewById(R.id.pwdViewField);
		EditText infoText = (EditText) findViewById(R.id.otherViewField);

		boolean on = ((ToggleButton)view).isChecked();
		
		usnText.setEnabled(on);
		pwdText.setEnabled(on);
		infoText.setEnabled(on);
		titleText.setEnabled(on);
		
		usnText.setFocusableInTouchMode(on);
		pwdText.setFocusableInTouchMode(on);
		infoText.setFocusableInTouchMode(on);
		titleText.setFocusableInTouchMode(on);
		
		titleText.setFocusable(on);
		usnText.setFocusable(on);
		pwdText.setFocusable(on);
		infoText.setFocusable(on);
		
		

	}

	public void add(View view) {

		EditText titleText = (EditText) findViewById(R.id.titleViewField);
		EditText usnText = (EditText) findViewById(R.id.usnViewField);
		EditText pwdText = (EditText) findViewById(R.id.pwdViewField);
		EditText infoText = (EditText) findViewById(R.id.otherViewField);

		String title = titleText.getText().toString();
		String usn = usnText.getText().toString();
		String pwd = pwdText.getText().toString();
		String info = infoText.getText().toString();

		title=title.trim();

		if(title.length()==0){
			TextView pwdLabel=(TextView) findViewById(R.id.titleViewLabel);
			pwdLabel.setText("Please Insert a Title:");
			pwdLabel.setTextColor(Color.RED);
			return;
		}

		String buffer=loadAllInstances(key, cryptMD5(username)+"_titles.txt");
		if(buffer.contains("\n1"+title+"\n")){
			TextView pwdLabel=(TextView) findViewById(R.id.titleViewLabel);
			pwdLabel.setText("Title already Used:");
			pwdLabel.setTextColor(Color.RED);
			return;
		}
		buffer=buffer+title+"\n";
		writeAllInstances(key, buffer, cryptMD5(username)+"_titles.txt");

		buffer=loadAllInstances(key, cryptMD5(username)+"_instances.txt");   	
		buffer=buffer+"1"+title+"\n2"+usn+"\n3"+pwd+"\n4"+info+"\n";
		writeAllInstances(key, buffer, cryptMD5(username)+"_instances.txt");
		buffer="";
		
		showToast("Data Successfully Added!");
		
		titleText.setText("");
		usnText.setText("");
		pwdText.setText("");
		infoText.setText("");
		
	}
	
	public void showToast(String message){
		Context context = getApplicationContext();
		CharSequence text = message;
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}

	public void close(View view) {
		this.finish();
	}

	public String loadAllInstances(String key, String filename) {

		File f = new File(getExternalFilesDir(null), filename);
		FileReader fr = null;
		BufferedReader br = null;
		String buffer="";
		try{
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			while(true){
				String tmp = br.readLine();
				if(tmp==null){br.close(); break;}
				buffer=buffer+tmp;
			}
		}
		catch (IOException e) {      
			e.printStackTrace();
		}

		try {
			buffer=CryptoFunction.AES_Decrypt(buffer, key);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		return buffer;
	}

	public void writeAllInstances(String key, String buffer, String filename) {

		try {
			buffer=CryptoFunction.AES_Encrypt(buffer, key);
		} catch (InvalidKeyException e1) {
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (NoSuchPaddingException e1) {
			e1.printStackTrace();
		} catch (IllegalBlockSizeException e1) {
			e1.printStackTrace();
		} catch (BadPaddingException e1) {
			e1.printStackTrace();
		}

		File f = new File(getExternalFilesDir(null), filename);
		FileWriter fw = null;
		BufferedWriter bw = null;
		try{
			fw = new FileWriter(f, false);
			bw = new BufferedWriter(fw);
			bw.write(buffer);
			bw.close();
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}
	}



}
